package com.example.sample1

import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    private val CHANNEL = "sample.flutter.dev/battery";

    //和原生通信
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger,CHANNEL)
                .setMethodCallHandler { call, result ->
                    if(call.method == "getBatteryLevel"){
                        var batteryLevel = getBatteryLevel();
                        if(batteryLevel != -1){
                            result.success(batteryLevel);
                        }else{
                            result.error("UNAVAILABLE","Battery level not available",null);
                        }
                    }else{
                        result.notImplemented();
                    }
                }
    }

    private fun getBatteryLevel():Int{
        val batteryLevel:Int
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager;
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        }else{
            var intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL,-1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
        }
        return batteryLevel;
    }

}
